#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
创建数据库表结构
"""

import sys
import os
from sqlalchemy import create_engine
from datetime import datetime
import logging

# 添加当前目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from config import Config
from database import Base, Question, Submission, SubmissionDetail, LLMConfig, ClassConfig

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def create_all_tables():
    """创建所有数据库表"""
    try:
        # 创建数据库引擎
        engine = create_engine(Config.DATABASE_URL, echo=True)
        
        logger.info("开始创建数据库表...")
        
        # 创建所有表
        Base.metadata.create_all(bind=engine)
        
        logger.info("数据库表创建完成！")
        
        # 验证表是否创建成功
        from sqlalchemy import text
        with engine.connect() as conn:
            result = conn.execute(text("SELECT name FROM sqlite_master WHERE type='table';"))
            tables = result.fetchall()
            logger.info(f"创建的表: {[table[0] for table in tables]}")
            
        return True
        
    except Exception as e:
        logger.error(f"创建数据库表失败: {e}")
        return False

if __name__ == "__main__":
    try:
        print("开始创建数据库表...")
        if create_all_tables():
            print("\n🎉 数据库表创建成功！")
        else:
            print("\n❌ 数据库表创建失败！")
            sys.exit(1)
            
    except Exception as e:
        print(f"\n❌ 创建失败: {e}")
        sys.exit(1)